import { type ApiResponse, http, request } from "./index";

// 用户信息接口
interface UserInfo {
  id: number;
  name: string;
  email: string;
  avatar?: string;
}

// 登录参数接口
interface LoginParams {
  username: string;
  password: string;
}

// 登录响应接口
interface LoginResponse {
  token: string;
  userInfo: UserInfo;
}

// 示例1: 使用request实例
export const userService = {
  // 获取用户信息
  async getUserInfo(userId: number): Promise<ApiResponse<UserInfo>> {
    return request.get<UserInfo>(`/users/${userId}`);
  },

  // 更新用户信息
  async updateUserInfo(
    userId: number,
    data: Partial<UserInfo>,
  ): Promise<ApiResponse<UserInfo>> {
    return request.put<UserInfo>(`/users/${userId}`, data);
  },

  // 删除用户
  async deleteUser(userId: number): Promise<ApiResponse<void>> {
    return request.delete<void>(`/users/${userId}`);
  },

  // 登录
  async login(params: LoginParams): Promise<ApiResponse<LoginResponse>> {
    return request.post<LoginResponse>("/auth/login", params);
  },

  // 注册
  async register(
    params: LoginParams & { email: string },
  ): Promise<ApiResponse<UserInfo>> {
    return request.post<UserInfo>("/auth/register", params);
  },
};

// 示例2: 使用便捷方法http
export const productService = {
  // 获取产品列表
  async getProducts(params?: {
    page?: number;
    size?: number;
    category?: string;
  }) {
    return http.get<{ list: any[]; total: number }>("/products", { params });
  },

  // 创建产品
  async createProduct(data: {
    name: string;
    price: number;
    description?: string;
  }) {
    return http.post("/products", data);
  },

  // 更新产品
  async updateProduct(
    id: number,
    data: Partial<{ name: string; price: number; description: string }>,
  ) {
    return http.put(`/products/${id}`, data);
  },

  // 删除产品
  async deleteProduct(id: number) {
    return http.delete(`/products/${id}`);
  },
};

// 示例3: 自定义配置
export const fileService = {
  // 上传文件（不显示loading）
  async uploadFile(file: File): Promise<ApiResponse<{ url: string }>> {
    const formData = new FormData();
    formData.append("file", file);

    return request.post<{ url: string }>("/upload", formData, {
      showLoading: false, // 不显示loading
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });
  },

  // 下载文件
  async downloadFile(fileId: string): Promise<Blob> {
    const response = await request.get(`/files/${fileId}/download`, {
      responseType: "blob",
      showLoading: false,
    });
    return response.data;
  },
};

// 示例4: 错误处理
export const errorHandlingExample = {
  async riskyOperation() {
    try {
      // 这个请求可能会失败
      const result = await request.get("/api/risky-endpoint");
      console.log("操作成功:", result);
      return result;
    } catch (error) {
      // 错误已经被拦截器处理了，这里可以做额外的处理
      console.log("操作失败，但错误已经被拦截器处理");
      throw error;
    }
  },
};

// 示例5: 设置全局配置
export const setupGlobalConfig = () => {
  // 设置默认超时时间
  request.setDefaultConfig({
    timeout: 15000,
  });

  // 设置自定义请求头
  request.setHeader("X-Custom-Header", "custom-value");
  request.setHeader("X-Client-Version", "1.0.0");
};

// 使用示例
export const usageExamples = async () => {
  try {
    // 登录
    const loginResult = await userService.login({
      username: "testuser",
      password: "password123",
    });
    console.log("登录成功:", loginResult.data);

    // 获取用户信息
    const userInfo = await userService.getUserInfo(1);
    console.log("用户信息:", userInfo.data);

    // 获取产品列表
    const products = await productService.getProducts({ page: 1, size: 10 });
    console.log("产品列表:", products.data);

    // 上传文件
    const fileInput = document.createElement("input");
    fileInput.type = "file";
    fileInput.onchange = async (e) => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (file) {
        const uploadResult = await fileService.uploadFile(file);
        console.log("文件上传成功:", uploadResult.data.url);
      }
    };
    fileInput.click();
  } catch (error) {
    console.error("操作失败:", error);
  }
};
